import React, {Component} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置

import {
  Row,
  Col,
  Card,
  Form,
  Input,

  Icon,

  Dropdown,
  Popover,
  InputNumber,
  DatePicker,

  message,
  Badge,
  Divider,
  Steps,
  Upload,
  Collapse, Empty,
} from 'antd';
import {Select,Button , Table ,Modal,Pagination} from '@/components/CustomAntd'
const { MonthPicker, RangePicker } = DatePicker;
import UpdateModal from './UpdataModal';
import PermisstionModal from './PermissionModal';
import DetailModal from './DetailModal'

@connect(({no_plateform_role, loading}) => ({
  no_plateform_role,
  loading: loading.models.no_plateform_role,
}))
@Form.create()
class List extends Component {
  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'no_plateform_role/fetch',
      payload:{
        "page_num": 1,
        "page_size": 10
      },
    });
  }
  tableChange = (pagination, filters, sorter) => {
    const params = {
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };
    this.searchList(params);
  };
  searchList = (pagination)=>{
    const { no_plateform_role: {
      pagination :{
        page_num,
        page_size
      }
    },dispatch} = this.props;
    const pageInfo = pagination?pagination:{page_num,page_size}
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const valuesEnd = {
          ...pageInfo
        };
        if (values.role_name) {
          valuesEnd.role_name = values.role_name;
        }
        if (values.create_time && values.create_time.length > 0) {
          valuesEnd.created_time_from = moment(values.create_time[0]).format('YYYY-MM-DD HH:mm:ss');
          valuesEnd.created_time_to = moment(values.create_time[1]).format('YYYY-MM-DD HH:mm:ss');
        }
        const action = {
          type: `no_plateform_role/fetch`,
          payload: valuesEnd,
        };
        dispatch(action);
      }
    });
  }
  showUpdateModal =(modalType,id)=>{
    const {dispatch} = this.props;
    if (!modalType) return
    const parms = modalType ==='create' ? { modalType:modalType} :{ modalType:modalType ,role_id:id}
    dispatch({
      type: 'no_plateform_role/showUpdateModal',
      payload:parms,
    });
  }
  handleUpdateRole = (values)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'no_plateform_role/handleUpdateRole',
      payload: {
        ...values
      },
    }).then((r)=>{
      const parms = values.modalType === 'update' ? undefined :{'page_size': 10,'page_num': 1,}
      if (r) {
        this.searchList(parms)
        this.closeUpdateModal()
      }
    });
  }
  closeUpdateModal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'no_plateform_role/save',
      payload: {
        updateVisible: false,
      },
    });
  };
  //删除处理
  deleteList=(id)=> {
    const props = this.props;
    const _this = this;
    Modal.confirm({
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      okText: '确认',
      cancelText: '取消',
      icon: 'frown',
      onOk() {
        //发送删除请求
        props.dispatch({
          type: `no_plateform_role/deleteBegin`,
          payload: {
            role_id: id,
          },
          callback: (res) => {
            if (res.return_code === 'SUCCESS') {
              message.success('删除成功');
            }
            //代入当前分页状态重新查询一次

            _this.searchList();
          },
        });

      },
      onCancel() {
        return false;
      },
    });

  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={(e)=>{
        e.preventDefault();
        this.searchList({'page_size': 10,'page_num': 1,})
      }} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 60 }}>
            <Row align="middle">
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.roleManage.roleManage_list.role_name' })} :
                </div>
                {getFieldDecorator('role_name')(
                  <Input placeholder="请输入" style={{ width: '65%' }}/>,
                )}
              </Col>
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.roleManage.roleManage_list.create_time' })} :
                </div>
                {getFieldDecorator('create_time')(
                  <RangePicker
                    placeholder={['开始日期', '结束日期']}
                    showTime={{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }}
                    format="YYYY-MM-DD HH:mm:00"
                    style={{ width: '65%' }}
                  />,
                )}
              </Col>
            </Row>
          </div>
          <div style={{ height: '40px', fontSize: '16px' }}>
            <Row gutter={30}>
              <Col md={18} sm={24} align="left" style={{ paddingLeft: 10 }}>
                  <span>
                      <Button type="primary" onClick={()=>this.showUpdateModal('create')}>新建</Button>
                   </span>
              </Col>
              <Col md={6} sm={24} align="right" style={{ paddingLeft: 10 }}>
                  <span>
                    <Button type="primary" htmlType="submit">查询</Button>
                    <Button style={{marginLeft : 3}} htmlType="reset" onClick={()=>{this.props.form.resetFields()}}>重置</Button>
                  </span>
              </Col>
            </Row>
          </div>
        </div>
      </Form>
    )
  }
  handleUpdatePermisstion=(subFiles)=>{
    const { dispatch } = this.props;
    dispatch({
      type: `no_plateform_role/editBegin`,
      payload: {
        ...subFiles
      },
    }).then((r)=>{
      if(r){
        dispatch({
          type: 'no_plateform_role/save',
          payload: {
            permissionVisible :false,
            updateRoleId:undefined,
            permission:[],
            checked_permissions:[],
            href_checked_permissions : [],
          },
        })
      }
    })
  }
  setSystem=(id,type)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'no_plateform_role/showPermssionModal',
      payload: {
        role_id:id,
        type:type
        //permissionVisible: true,
      },
    });
  }
  saveState=(parms)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'no_plateform_role/save',
      payload: {
        ...parms
      },
    });
  }
  detailsList = (detail) =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'no_plateform_role/showDetail',
      payload: {
        role_id : detail.role_id
      },
    });
  }
  render() {
    const { no_plateform_role: {
      list,
      pagination,
      updateVisible,
      modalType,
      updateData,
      tenantList,
      permissionVisible,
      permission,
      checked_permissions,
      href_checked_permissions,
      updateRoleId,
      detailVisible,
      detailInfo,
      detail_permission,
    },loading} = this.props;
    const columns = [

      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.role_name' }),
        dataIndex: 'role_name',
        align: 'center',
        render: (text, record) => {
          return (
            <a onClick={() => this.detailsList(record)}>{record.role_name}</a>
          );
        },
      },
      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.create_user_id' }),
        dataIndex: 'create_user_name',
        align: 'center',
      },
      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.create_time' }),
        dataIndex: 'create_time',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'doIt',
        key: 'doIt',
        render: (text, record) => (
          <span className="table-operation">
              <a onClick={() => this.showUpdateModal('update',record.role_id)}>
               编辑
              </a>
              <Divider type="vertical"/>
               <a onClick={() => this.deleteList(record.role_id)}>
               删除
              </a>
              <Divider type="vertical"/>
              <a onClick={() => this.setSystem(record.role_id,'type_route')}>设置页面权限</a>
            <Divider type="vertical"/>
              <a onClick={() => this.setSystem(record.role_id,'type_component')}>设置非页面权限</a>
            </span>
        ),
        align: 'center',
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) =>
        `共有 ${parseInt(total)} 条数据 当前第${pagination.page_num}页`,
     /* onChange: (page, pageSize) => {

      },
      onShowSizeChange: (current, size) => {

      },*/
      ...pagination,
    };
    return (
      <PageHeaderWrapper>
        <div
          style={{
            backgroundColor: '#FFFFFF',
            paddingLeft: '5%',
            paddingRight: '5%',
          }}
        >
          {this.renderSimpleForm()}
          {
            list && list.length > 0 ?
              <Table
                dataSource={list}
                columns={columns}
                rowKey={record => record.role_id}
                onChange={this.tableChange}
                pagination={paginationProps}
                onShowSizeChange={this.onShowSizeChange}
              />
              :
              <Empty
                style={{ paddingBottom: 30, paddingTop: 15 }}
              />
          }
          {
            updateVisible ?
              <UpdateModal
                visible = {updateVisible}
                modalType={modalType}
                updateOnSubmit={this.handleUpdateRole}
                updateData={updateData}
                tenantList={tenantList}
                hideCancel = {this.closeUpdateModal}
              /> :[]
          }
          {
            permissionVisible?
              <PermisstionModal
                visible={permissionVisible}
                modalHandleCancel={()=>{this.saveState({permissionVisible:false})}}
                subPermisstion={this.handleUpdatePermisstion}
                checked_permissions={checked_permissions}
                saveState={this.saveState}
                permission={permission}
                updateRoleId={updateRoleId}
                href_checked_permissions={href_checked_permissions}
              /> :[]
          }
          {
            detailVisible ?
              <DetailModal
                closeDatails={()=>{this.saveState({detailVisible:false})}}
                detailVisible={detailVisible}
                row={detailInfo}
                detail_permission={detail_permission}
              /> :[]
          }
        </div>
      </PageHeaderWrapper>
    );
  }
}
export default List